<template>
  <div class="messages-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h2>留言管理</h2>
        <p>管理访客留言，包括查看、回复、删除等操作</p>
      </div>
      <div class="header-right">
        <el-button type="danger" @click="batchDelete" :disabled="!selectedMessages.length">
          批量删除
        </el-button>
      </div>
    </div>

    <!-- 搜索留言 -->
    <div class="search-section" style="margin-bottom: 20px;">
      <el-input
        v-model="searchKeyword"
        placeholder="搜索留言内容/姓名/邮箱/电话"
        clearable
        style="width: 300px"
        @keyup.enter="handleSearch"
      >
        <template #append>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
        </template>
      </el-input>
    </div>

    <!-- 留言列表 -->
    <div class="messages-list">
      <el-card>
        <el-table
          v-loading="loading"
          :data="messages"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          
          <el-table-column label="留言者" width="120">
            <template #default="{ row }">
              <div class="message-user">
                <el-avatar :size="32" :src="row.avatar">
                  {{ row.guest_name?.charAt(0) || 'U' }}
                </el-avatar>
                <div class="user-info">
                  <div class="name">{{ row.guest_name }}</div>
                </div>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column prop="guest_email" label="邮箱" width="180" />
          
          <el-table-column prop="content" label="留言内容" min-width="300">
            <template #default="{ row }">
              <div class="message-content">
                <p>{{ row.content }}</p>
                <div v-if="row.reply" class="reply-content">
                  <el-tag type="success" size="small">回复：</el-tag>
                  <span>{{ row.reply }}</span>
                </div>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column prop="created_at" label="留言时间" width="120">
            <template #default="{ row }">
              {{ formatDate(row.created_at) }}
            </template>
          </el-table-column>
          
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-button
                type="primary"
                size="small"
                @click="replyMessage(row)"
              >
                回复
              </el-button>
              <el-button
                type="danger"
                size="small"
                @click="deleteMessage(row.id)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="pagination.current_page"
            v-model:page-size="pagination.per_page"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 回复留言对话框 -->
    <el-dialog
      v-model="replyDialogVisible"
      title="回复留言"
      width="600px"
    >
      <div class="reply-dialog">
        <div class="original-message">
          <h4>原留言：</h4>
          <div class="message-info">
            <p><strong>{{ currentMessage.guest_name }}</strong> ({{ currentMessage.guest_email }})</p>
            <p>{{ currentMessage.content }}</p>
            <p class="message-time">{{ formatDate(currentMessage.created_at) }}</p>
          </div>
        </div>
        
        <div class="reply-form">
          <h4>回复内容：</h4>
          <el-input
            v-model="replyContent"
            type="textarea"
            :rows="4"
            placeholder="请输入回复内容"
            maxlength="500"
            show-word-limit
          />
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="replyDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitReply" :loading="replying">
            发送回复
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { messageApi } from '@/api/admin'

// 留言列表
const messages = ref([])
const selectedMessages = ref([])
const loading = ref(false)

// 分页
const pagination = ref({
  current_page: 1,
  per_page: 20,
  total: 0
})

// 回复对话框
const replyDialogVisible = ref(false)
const currentMessage = ref({})
const replyContent = ref('')
const replying = ref(false)

// 搜索关键词
const searchKeyword = ref('')
const handleSearch = () => {
  pagination.value.current_page = 1
  fetchMessages()
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN') + ' ' + date.toLocaleTimeString('zh-CN', { hour12: false })
}

// 获取留言列表
const fetchMessages = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.value.current_page,
      per_page: pagination.value.per_page
    }
    if (searchKeyword.value) params.search = searchKeyword.value
    const response = await messageApi.getMessages(params)
    messages.value = response.data || []
    pagination.value = {
      current_page: response.meta?.current_page || 1,
      per_page: response.meta?.per_page || 20,
      total: response.meta?.total || 0
    }
  } catch (error) {
    console.error('获取留言列表失败:', error)
    ElMessage.error('获取留言列表失败')
  } finally {
    loading.value = false
  }
}

// 选择变化
const handleSelectionChange = (selection) => {
  selectedMessages.value = selection
}

// 分页大小变化
const handleSizeChange = (size) => {
  pagination.value.per_page = size
  pagination.value.current_page = 1
  fetchMessages()
}

// 当前页变化
const handleCurrentChange = (page) => {
  pagination.value.current_page = page
  fetchMessages()
}

// 回复留言
const replyMessage = (message) => {
  currentMessage.value = message
  replyContent.value = message.reply || ''
  replyDialogVisible.value = true
}

// 提交回复
const submitReply = async () => {
  if (!replyContent.value.trim()) {
    ElMessage.warning('请输入回复内容')
    return
  }
  
  try {
    replying.value = true
    await messageApi.replyMessage(currentMessage.value.id, {
      content: replyContent.value
    })
    
    ElMessage.success('回复发送成功')
    replyDialogVisible.value = false
    fetchMessages()
  } catch (error) {
    console.error('回复失败:', error)
    ElMessage.error('回复失败')
  } finally {
    replying.value = false
  }
}

// 删除留言
const deleteMessage = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这条留言吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await messageApi.deleteMessage(id)
    ElMessage.success('删除成功')
    fetchMessages()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除留言失败:', error)
      ElMessage.error('删除留言失败')
    }
  }
}

// 批量删除
const batchDelete = async () => {
  if (!selectedMessages.value.length) {
    ElMessage.warning('请选择要删除的留言')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedMessages.value.length} 条留言吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const ids = selectedMessages.value.map(message => message.id)
    await messageApi.batchDelete(ids)
    
    ElMessage.success('批量删除成功')
    selectedMessages.value = []
    fetchMessages()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  }
}

// 组件挂载
onMounted(() => {
  fetchMessages()
})
</script>

<style scoped lang="scss">
.messages-page {
  background: #fafbfc;
  min-height: 100vh;
  padding: 32px 0;

  .page-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 24px;
  }

  .page-title {
    font-size: 24px;
    font-weight: 700;
    color: #222;
  }

  .messages-list {
    .message-user {
      display: flex;
      align-items: center;
      gap: 8px;

      .user-info {
        .name {
          font-weight: 500;
          color: #303133;
        }
      }
    }

    .message-content {
      p {
        margin: 0 0 8px 0;
        line-height: 1.5;
      }

      .reply-content {
        background: #f5f7fa;
        padding: 8px 12px;
        border-radius: 4px;
        margin-top: 8px;

        span {
          margin-left: 8px;
          color: #606266;
        }
      }
    }

    .pagination-wrapper {
      margin-top: 24px;
      display: flex;
      justify-content: center;
    }
  }
}

.reply-dialog {
  .original-message {
    margin-bottom: 20px;
    padding: 16px;
    background: #f5f7fa;
    border-radius: 6px;

    h4 {
      margin: 0 0 12px 0;
      color: #303133;
    }

    .message-info {
      p {
        margin: 0 0 8px 0;
        line-height: 1.5;

        &:last-child {
          margin-bottom: 0;
        }
      }

      .message-time {
        font-size: 12px;
        color: #909399;
      }
    }
  }

  .reply-form {
    h4 {
      margin: 0 0 12px 0;
      color: #303133;
    }
  }
}

@media (max-width: 768px) {
  .messages-page {
    padding: 16px 0;
  }
  .messages-table {
    border-radius: 12px;
    padding: 12px;
  }
  .page-title {
    font-size: 18px;
  }
}
</style> 